//
//  CaptureDeviceViewModel.swift
//  二维码扫描
//
//  Created by apple on 2021/6/9.
//

import Foundation
import AVFoundation

class CaptureDeviceViewModel: NSObject, ObservableObject {
    public static let shared = CaptureDeviceViewModel()
    
    @Published var externalVideoDevice = [CaptureDevice]()    // 外接摄像头
    @Published var inWideAngleVideoDevice = [CaptureDevice]() // 内置摄像头
    @Published var devices = [CaptureDevice]()                // 所有设备
    @Published var isAuthorization = false        //设备未取权限
    @Published var isContainsVideoDevice = false      //视频设备
    @Published var isExternalVideoDevice = false      //外接视频设备
    @Published var isInWideAngleDevice = false        //内置视频设备
    @Published var videoUrlArray = [URL]()        //当前操作视频路径数组
    @Published var videoUrlStrArray = [String]()        //当前操作视频路径数组 String
    
    @Published var showVideoNum : Int8 = 2    //在用设备数量
    @Published var showVideoDevices = [CaptureDevice]()     //在用设备
    
    override private init() {
        super.init()
   
        //校验设备权限
        let authorization = checkAuthorizationStatus(session: AVCaptureSession())
        if authorization == false {
            self.isAuthorization = false
            return
        } else {
            self.isAuthorization = true
        }
        
        //发现设备
//        self.externalVideoDevice = discoveryExternalDevices()
//        self.inWideAngleVideoDevice = discoveryInWideAngleDevices()
        self.devices = discoveryDevices()

        if inWideAngleVideoDevice.count <= 0 {
            self.isInWideAngleDevice = false
        } else {
            self.isInWideAngleDevice = true
        }
        if externalVideoDevice.count <= 0 {
            self.isExternalVideoDevice = false
        } else {
            self.isExternalVideoDevice = true
        }
        if devices.count <= 0 {
            self.isContainsVideoDevice = false
        } else {
            self.isContainsVideoDevice = true
        }
        
        if isInWideAngleDevice == false && isExternalVideoDevice == false && isContainsVideoDevice == false {
            return
        }
    }
}

extension CaptureDeviceViewModel {
    //应用权限
    func checkAuthorizationStatus(session: AVCaptureSession) -> Bool {
        var state: Bool = false
        let authorizationStatus: AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        switch authorizationStatus {
        case AVAuthorizationStatus.notDetermined:
//            log.debug("notDetermined") //未定义
            state = false
        case AVAuthorizationStatus.restricted:
//            log.debug("restricted") //无权限（因某些原因，系统拒绝权限）
            state = false
        case AVAuthorizationStatus.denied:
//            log.debug("denied")  //无权限（用户拒绝）
            state = false
        case AVAuthorizationStatus.authorized:
//            log.debug("authorized") //可用
            state = true
        default:
//            log.debug("notDetermined")
            state = false
        }
        return state
    }
    
    //发现外接设备
    func discoveryExternalDevices() -> [CaptureDevice] {
        let externalUnknown_video = AVCaptureDevice.DiscoverySession.init(deviceTypes: [AVCaptureDevice.DeviceType.externalUnknown], mediaType: AVMediaType.video, position: .unspecified)
        for ex_video in externalUnknown_video.devices {
            let captureDevice = CaptureDevice.init(captureDevice: ex_video)
            self.externalVideoDevice.append(captureDevice)
        }
        return self.externalVideoDevice
    }
    
    //发现内接设备
    func discoveryInWideAngleDevices() -> [CaptureDevice] {
        let inWideAngle_video = AVCaptureDevice.DiscoverySession.init(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .unspecified)
        for in_video in inWideAngle_video.devices {
            let captureDevice = CaptureDevice.init(captureDevice: in_video)
            self.inWideAngleVideoDevice.append(captureDevice)
        }
        return self.inWideAngleVideoDevice
    }
    
    //总设备
    func discoveryDevices() -> [CaptureDevice] {
        let inWideAngle_video = AVCaptureDevice.DiscoverySession.init(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .unspecified)
        var index = 0
        for in_video in inWideAngle_video.devices {
            if index < showVideoNum {
                let captureDevice = CaptureDevice.init(captureDevice: in_video)
                captureDevice.serialNumber = index
                self.inWideAngleVideoDevice.append(captureDevice)
                index += 1
            } else {
                break
            }
        }
        let externalUnknown_video = AVCaptureDevice.DiscoverySession.init(deviceTypes: [AVCaptureDevice.DeviceType.externalUnknown], mediaType: AVMediaType.video, position: .unspecified)
        for ex_video in externalUnknown_video.devices {
            if index < showVideoNum {
                let captureDevice = CaptureDevice.init(captureDevice: ex_video)
                captureDevice.serialNumber = index
                self.externalVideoDevice.append(captureDevice)
                index += 1
            } else {
                break
            }
        }
        self.devices.append(contentsOf: inWideAngleVideoDevice)
        self.devices.append(contentsOf: externalVideoDevice)
        
        return self.devices
    }
    
    //是否视频采集设备
    func isCaptureVideoDevice() -> Bool {
        var isCaptureVideoDevice = false
        if isInWideAngleDevice == false && isExternalVideoDevice == false && isContainsVideoDevice == false {
            isCaptureVideoDevice = false
        } else {
            isCaptureVideoDevice = true
        }
        
        return isCaptureVideoDevice
    }

    //隐藏视图
    func hideCaptureDeviceLayer(device: CaptureDevice){
        device.videoPreviewLayer.isHidden = true
    }
    
    func hideAllCaptureDeviceLayer(devices: [CaptureDevice]){
        if devices.count <= 0 {
            return
        }
        for device in devices {
            device.videoPreviewLayer.isHidden = true
        }
    }
    
    //显示视图
    func displayCaptureDeviceLayer(device: CaptureDevice){
        device.videoPreviewLayer.isHidden = false
    }
    
    func displayAllCaptureDeviceLayer(devices: [CaptureDevice]){
        if devices.count <= 0 {
            return
        }
        for device in devices {
            device.videoPreviewLayer.isHidden = false
        }
    }
}
